package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.api.*;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.config.template.HuanXinTemplate;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.pojo.Question;
import com.tanhua.model.pojo.Settings;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeListVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UsersService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HuanXinTemplate hanXinTemplate;


    //根据id查询用户详情
    public UserInfoVo findUserInfo(Long userID) {
        //1 根据id查询用户详情
        UserInfo userInfo = userInfoApi.findById(userID);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo);

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.updateById(userInfo);
    }

    public SettingsVo findSettings() {
        //1. 创建vo对象
        SettingsVo vo = new SettingsVo();

        //2. 设置用户id和手机号
        vo.setId(UserHolder.getUserId());
        vo.setPhone(UserHolder.getMobile());

        //3. 根据用户id查询陌生人问题
        Question question = questionApi.findById(UserHolder.getUserId());
        //获取陌生人的问题，如果有值，就是用该值，如果没有值，设置默认的问题
        String txt = question == null ? "你喜欢java吗?" : question.getTxt();
        vo.setStrangerQuestion(txt);

        //4. 根据用户id查询通知设置数据
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());
        if (settings != null) {
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
        }

        //返回结果
        return vo;
    }

    //保存陌生人问题
    public void questions(String content) {
        //1. 根据用户id查询陌生人问题
        Question question = questionApi.findById(UserHolder.getUserId());

        //2. 判断数据是否存在
        if (question == null) {
            //不存在就新增
            question = new Question();
            question.setUserId(UserHolder.getUserId());
            question.setTxt(content);

            questionApi.save(question);
        } else {
            //存在就修改
            question.setTxt(content);
            questionApi.update(question);
        }

    }

    //通知设置 - 保存
    public void notifications(Map param) {
        Boolean likeNotification = (Boolean) param.get("likeNotification");
        Boolean pinglunNotification = (Boolean) param.get("pinglunNotification");
        Boolean gonggaoNotification = (Boolean) param.get("gonggaoNotification");

        //1 根据用户id查询通知设置
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());

        //2 判断通知设置数据是否存在
        if (settings == null) {
            //不存在就新增
            settings = new Settings();
            settings.setUserId(UserHolder.getUserId());
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);

            settingsApi.save(settings);
        } else {
            //存在就更新
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);

            settingsApi.update(settings);
        }


    }

    //分页查询黑名单
    public PageResult blacklist(Integer page, Integer pagesize) {
        //1 调用API分页查询 当前用户 的黑名单用户的用户详情
        Page<UserInfo> pages = userInfoApi.findByPage(UserHolder.getUserId(), page, pagesize);
        List<UserInfo> userInfoList = pages.getRecords();
        return new PageResult(page, pagesize, (int) pages.getTotal(), userInfoList);

        ////2 封装返回的用户详情vos
        //List<UserInfoVo> vos = new ArrayList<>();
        //for (UserInfo userInfo : pages.getRecords()) {
        //    UserInfoVo vo = new UserInfoVo();
        //    BeanUtils.copyProperties(userInfo, vo);
        //    if (userInfo.getAge() != null) {
        //        vo.setAge(userInfo.getAge().toString());
        //    }
        //
        //    vos.add(vo);
        //}
        //
        ////3 封装返回的分页对象
        //return new PageResult(page, pagesize, (int) pages.getTotal(), vos);
    }

    //移除黑名单用户
    public void deleteBlacklist(Long uid) {
        //调用Api，实现删除功能
        blackListApi.deleteBlacklist(UserHolder.getUserId(), uid);
    }



    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     * 请求参数：
     * userId 当前登录用户id
     * 响应结果：
     * eachLoveCount  互相喜欢()  loveCount 喜欢 fanCount 粉丝 Integer 类型
     * 可以使用Map 集合来封装
     */
    public Map<String,Integer> counts(Long userId) {
        Map<String,Integer> map = userLikeApi.counts(userId);
        return map;
    }

    //互相喜欢
    public PageResult eachLove(Integer type, Integer page, Integer pagesize) {
            //1 获取用户id
        Long userId = UserHolder.getUserId();
            //2 分页查询好友表
            List<Friend> friendList = friendApi.findBypage(userId,page,pagesize);
            //3 获取好友id
            //判断好友列表是否为空
            if(CollectionUtil.isEmpty(friendList)){
                throw new RuntimeException("暂无好友信息");
            }
            List<Long> friendIds = CollectionUtil.getFieldValues(friendList, "friendId", Long.class);

            //4 查询好友详情
            if(CollectionUtil.isEmpty(friendIds)){
                throw new RuntimeException("好友id为空");
            }
            Map<Long,UserInfo> map = userInfoApi.findbyids(friendIds);
            //5 封装UserLikeListsVo对象
        List<UserLikeListVo> vos = new ArrayList<>();
        for (Friend friend : friendList) {
                UserInfo userInfo = map.get(friend.getFriendId());
                UserLikeListVo vo = UserLikeListVo.init(userInfo);
                vos.add(vo);
            }
            //6 返回数据
        return new PageResult(page,pagesize,0,vos);


    }

    /**
     * 分页查询 喜欢
     *
     * 请求参数：
     * type 查询类型（此方法为查询互相喜欢） page 当前页数  pagesize 每页条数
     * 响应结果：
     * 分页对象 PageResult
     * */
    public PageResult love(Integer type, Integer page, Integer pagesize) {
        //1.构建用户id
        Long userId = UserHolder.getUserId();
        //2.判断查询类型 2 喜欢  3 粉丝 (以废弃)

        /*查询双向喜欢表数据*/
        /*将两个表中重复数据排除掉*/
        List<Friend> friends = friendApi.findBypage(userId, page, pagesize);
        List<Long> likeEachList = new ArrayList<>();
        if(friends != null){
            likeEachList = friends.stream().map(s->s.getFriendId()).collect(Collectors.toList()); //获取互相喜欢好友id
        }


        //3.查询喜欢表
        List<UserLike> userLikeList = userLikeApi.findByPage(type, page, pagesize,userId);

        //4.提取好友id 判断类型  2 喜欢  3 粉丝  然后提取不同的id

        List<Long> idsList = new ArrayList<>();
        List<Long> onlyList = new ArrayList<>();
        if (type == 2) {
            if (CollectionUtil.isEmpty(userLikeList)) {
                throw new RuntimeException("【喜欢列表为空！！】");
            }
            idsList = CollectionUtil.getFieldValues(userLikeList, "likeUserId", Long.class);

            for (Long aLong : idsList) {
                if(!likeEachList.contains(aLong)){
                    onlyList.add(aLong);
                }
            }
//            idsList = onlyLoveList; //将新集合替代原来的集合

        } else if (type == 3) {
            if (CollectionUtil.isEmpty(userLikeList)) {
                throw new RuntimeException("【粉丝列表为空！！】");
            }
            idsList = CollectionUtil.getFieldValues(userLikeList, "userId", Long.class);
            for (Long aLong : idsList) {
                if(!likeEachList.contains(aLong)){
                    onlyList.add(aLong);
                }
            }
//            idsList = onlyLoveList; //将新集合替代原来的集合

        }

        //5.查询好友详情
        Map<Long, UserInfo> map = userInfoApi.findbyids(onlyList);

        //6.封装UserLikeLikesVo对象
        List<UserLikeListVo> userLikeListVos = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            UserInfo userInfo = null;
            if (type == 2 ) {
                userInfo = map.get(userLike.getLikeUserId());
            } else if (type == 3) {
                userInfo = map.get(userLike.getUserId());
            }

            if (userInfo != null) {
                UserLikeListVo userLikeListVo = UserLikeListVo.init(userInfo, userLike);
                userLikeListVos.add(userLikeListVo);
            }

        }
        //7.返回
        return new PageResult(page, pagesize, 0, userLikeListVos);
    }


    /**
     *  分页查询 粉丝
     *
     * 请求参数：
     * type 查询类型（此方法为查询互相喜欢） page 当前页数  pagesize 每页条数
     * 响应结果：
     * 分页对象 PageResult
     * */
    public PageResult fan(Integer type, Integer page, Integer pagesize) {
        return love(type,page,pagesize);
    }


    /**
     * 粉丝 - 喜欢
     * 请求参数：
     * userId 当前登录用户id    likeUserId  喜欢用户的id
     * 响应结果：
     * null
     */

    public void saveLove(Long userId, Long likeUserId) {
        //1.封装UserLike表
        UserLike userLike = new UserLike();
        userLike.setUserId(userId);//用户id
        userLike.setLikeUserId(likeUserId);//我喜欢的用户id
        userLike.setIsLike(true);//是否互相喜欢
        userLike.setCreated(System.currentTimeMillis());//创建时间
        //2.保存
        userLikeApi.saveLove(userLike);

        //3.判断双方是否为互相喜欢
        Boolean exists = userLikeApi.exists(userId, likeUserId);

        if (exists) {
            //4.如果是好友表添加
            friendApi.save(userId, likeUserId);

            //5.添加环信好友
            hanXinTemplate.addContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + likeUserId);
        }
    }


    /**
     * 粉丝 - 取消喜欢
     * 请求参数：
     * userId 当前登录用户id    likeUserId  喜欢用户的id
     * 响应结果：
     * null
     */
    public void deleteLove(Long userId, Long likeUserId) {
        //1.判断双方是否为相互喜欢
        Boolean exists = userLikeApi.exists(userId, likeUserId);
        //2.数据库删除此条数据
        userLikeApi.deleteLove(userId, likeUserId);

        if (exists) {
            //3.如何互相喜欢 则删除 环信好友关系
            hanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + likeUserId);

            //4.删除好友表
            friendApi.deleteFriend(userId, likeUserId);
        }
    }
}
